package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.annotation.RepeatSubmit;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.Dept;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.bean.BeanUtils;
import com.xhh.nphm.system.domain.TwfSendBackEty;
import com.xhh.nphm.system.domain.TworkFormBaseEty;
import com.xhh.nphm.system.domain.TworkFormLogEty;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.mapper.DeptMapper;
import com.xhh.nphm.system.service.*;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/system/sendBack")
public class WfSendBackController extends BaseController {
    String prefix = "system/sendBack";
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private IWfSendBackService wfSendBackService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IWorkFormBaseService workFormBaseService;
    @Autowired
    private ITelWFLogService telWFLogService;
    @Autowired
    private CommonServiceImpl commonService;

    @Autowired
    private BaiduApiController baiduApiController;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private SendSonCtrl sendSonCtrl;



    /**
     * 拟办部门页面
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/proposed/{pkId}")
    public ModelAndView proposed(@PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(pkId);
        TwfSendBackEty sendBackEty = tworkFormBaseEty.getTwfSendBackEty();
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", tworkFormBaseEty);
        map.put("wfId", tworkFormBaseEty.getPkId());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());
        map.put("deptId", user.getDeptId());
        map.put("sendTime",DateUtils.getTime());
        return new ModelAndView("system/test/deptdiag");
    }

    /**
     * 进入修改拟派工单的页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/editDept/{wfId}/{pkId}")
    public ModelAndView editDept(@PathVariable("wfId") Integer wfId, @PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(wfId);
        TwfSendBackEty sendBackEty = wfSendBackService.getById(pkId);
        tworkFormBaseEty.setTwfSendBackEty(sendBackEty);
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", tworkFormBaseEty);
        map.put("wfId", tworkFormBaseEty.getPkId());
        map.put("sdeptName", sendBackEty.getSdeptName());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());

        return new ModelAndView("system/test/editDeptDiag");
    }

    /**
     * 修改拟派工单信息
     * @param tworkFormBaseEty 带有拟派工单的电话工单
     * @return 响应结果
     */
    @PostMapping("/editDept")
    public AjaxResult editDept(TworkFormBaseEty tworkFormBaseEty) {
        //保存响应结果
        boolean flag = false;
        TwfSendBackEty twfSendBackEty = tworkFormBaseEty.getTwfSendBackEty();
//        if (twfSendBackEty.getWfId() > 0) {
            UpdateWrapper<TwfSendBackEty> sbWrapper = new UpdateWrapper<>();
            sbWrapper
                    .set("SeqCode", twfSendBackEty.getSeqCode())
                    .set("SeqName", twfSendBackEty.getSeqName())
                    .set("SbdeptId", twfSendBackEty.getSbdeptId())
                    .set("SbdeptName", twfSendBackEty.getSbdeptName())
                    .set("SortCode", twfSendBackEty.getSortCode())
                    .set("SortName", twfSendBackEty.getSortName())
                    .set("DealCode", twfSendBackEty.getDealCode())
                    .set("DealName", twfSendBackEty.getDealName())
                    .set("SendDesc", twfSendBackEty.getSendDesc())
                    .set("BackLimit", twfSendBackEty.getBackLimit())
                    .set("SendRemark", twfSendBackEty.getSendRemark())
                    .eq("PkId", twfSendBackEty.getPkId());
            //执行修改方法
            flag = wfSendBackService.update(sbWrapper);
            //判断是否修改成功
            if (flag) {
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                TworkFormLogEty etyLog = new TworkFormLogEty();
                //[tWorkFormBase]PkId
                etyLog.setWfId(twfSendBackEty.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                String temp = "调整办理部门及要求(" + twfSendBackEty.getSbdeptName() + ")";
                etyLog.setOpAction("修改");
                etyLog.setOpBtnId(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(1);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                telWFLogService.save(etyLog);
            }
//        }
        return toAjax(flag);
    }

    /**
     * 2023/1/10
     * 修改TwfSendBackEty工单信息
     * @param twfSendBackEty
     * @return 响应结果
     */
    @PostMapping("/editDeptJson")
    public AjaxResult editDeptJson(TwfSendBackEty twfSendBackEty) {
        //保存响应结果
        boolean flag = false;
        // if (twfSendBackEty.getWfId() > 0) {
            UpdateWrapper<TwfSendBackEty> sbWrapper = new UpdateWrapper<>();
            sbWrapper
                    .set("SeqCode", twfSendBackEty.getSeqCode())
                    .set("SeqName", twfSendBackEty.getSeqName())
                    .set("SbdeptId", twfSendBackEty.getSbdeptId())
                    .set("SbdeptName", twfSendBackEty.getSbdeptName())
                    .set("SortCode", twfSendBackEty.getSortCode())
                    .set("SortName", twfSendBackEty.getSortName())
                    .set("DealCode", twfSendBackEty.getDealCode())
                    .set("DealName", twfSendBackEty.getDealName())
                    .set("SendDesc", twfSendBackEty.getSendDesc())
                    .set("BackLimit", twfSendBackEty.getBackLimit())
                    .set("SendRemark", twfSendBackEty.getSendRemark())
                    .set("isDelay", twfSendBackEty.getIsDelay())
                    .eq("PkId", twfSendBackEty.getPkId());
            //执行修改方法
            flag = wfSendBackService.update(sbWrapper);
            //判断是否修改成功
            if (flag) {
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                TworkFormLogEty etyLog = new TworkFormLogEty();
                //[tWorkFormBase]PkId
                etyLog.setWfId(twfSendBackEty.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                String temp = "调整办理部门及要求(" + twfSendBackEty.getSbdeptName() + ")";
                etyLog.setOpAction("修改");
                etyLog.setOpBtnId(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(1);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                telWFLogService.save(etyLog);
            }
       // }
        return toAjax(flag);
    }

    /**
     * 拟派工单
     * resendType 1重新派单
     * 创建工单后的派单
     * 重新派单
     * @param
     * @return
     */
    @RequestMapping("simulacrum")
    @RepeatSubmit
    public AjaxResult simulacrum(TwfSendBackEty twfSendBackEty, Integer resendType, String zpFlag) {
        if (IS_GAOXIN()){
            return simulacrum_gxq(twfSendBackEty,resendType,zpFlag);
        }else{
            return simulacrum_general(twfSendBackEty,resendType);
        }
    }



    public AjaxResult simulacrum_general(TwfSendBackEty twfSendBackEty, Integer resendType) {
        String deptId = getSysUser().getDeptId().toString();
        if (twfSendBackEty.getFpDirect() == 1) {
            //xnb直派
            simulacrumXnb(twfSendBackEty,deptId);
        }
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(twfSendBackEty.getWfId());
        TwfSendBackEty etyMain = new TwfSendBackEty();
        if (tworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(tworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(tworkFormBaseEty.getCallId());
            etyMain.setTapeId(tworkFormBaseEty.getTapeId());
            etyMain.setWfId(tworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if (!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(twfSendBackEty.getSeqCode());
        etyMain.setSeqName(twfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(twfSendBackEty.getSendDesc());
        etyMain.setSdeptId(twfSendBackEty.getSdeptId());
        etyMain.setSdeptName(twfSendBackEty.getSdeptName());
        etyMain.setSuserNo(twfSendBackEty.getSuserNo());
        etyMain.setSuserName(twfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(twfSendBackEty.getSendRemark());
        etyMain.setSattachPath(twfSendBackEty.getSattachPath());
        etyMain.setSattachName(twfSendBackEty.getSattachName());
        etyMain.setSendSpare(twfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(twfSendBackEty.getDealName());
        etyMain.setBackLimit(twfSendBackEty.getBackLimit());
        etyMain.setIsGoBack(twfSendBackEty.getIsGoBack());
        //TODO：promisesTime不清楚怎么来的
        etyMain.setPromisesTime(twfSendBackEty.getBackLimit());
//        bDeptId = arrDetpIdX[i];
//        bDeptName = arrDetpNameX[i];
        if (twfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (twfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(twfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(twfSendBackEty.getSbdeptName());
        //重新派单，页面上拿不到父派单id
        Integer pid = twfSendBackEty.getPid();
        if(!"304".equals(deptId) && (pid == null || pid <= 0)) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<TwfSendBackEty> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", twfSendBackEty.getWfId());
            queryWrapper.eq("SBDeptId",deptId);
            queryWrapper.orderByDesc("pkId");
            List<TwfSendBackEty> list = wfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        etyMain.setPid(pid);
        int row = 0;
        boolean flag = false;
        //拟派多个部门
        if(twfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = twfSendBackEty.getSbdeptId().split(",");
            String[] names = twfSendBackEty.getSbdeptName().split(",");
            String sendDesc = twfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                etyMain.setSendDesc(sendDesc.replace(twfSendBackEty.getSbdeptName(),names[i]));
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                flag = wfSendBackService.save(etyMain);
                if (flag) {
                    row = 1;
                    // 记录电话派单操作日志
                    SysUser user = ShiroUtils.getSysUser();
                    //todo 日志
                    TworkFormLogEty etyLog = new TworkFormLogEty();
                    etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(user.getDeptId().toString());
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnId(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交内容概要：" + desc);
                    etyLog.setEffectFlag(1);
                    telWFLogService.save(etyLog);
                }
            }
        }
        //拟派一个部门
        else {
            flag = wfSendBackService.save(etyMain);
            if (flag) {
                row = 1;
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                //todo 日志
                TworkFormLogEty etyLog = new TworkFormLogEty();
                etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                etyLog.setOpAction("提交初稿");
                etyLog.setOpBtnId(-1);
                String temp = "";
                String desc = "";
                temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                desc = "主办：";
                desc += temp;
                etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                etyLog.setWsOpen(1); //website ShowFlag
                etyLog.setOpDesc("提交内容概要：" + desc);
                etyLog.setEffectFlag(1);
                telWFLogService.save(etyLog);
            }
        }

        //更新父级派单状态 etyMain新增下派单子的id
        commonDao.proTsubBackState(twfSendBackEty.getWfId(),etyMain.getPkId());
//        if(!"304".equals(deptId)) {
//            commonDao.proTsubBackState(twfSendBackEty.getWfId(),etyMain.getPkId());
//        }
        return toAjax(row);
    }

    public AjaxResult simulacrum_gxq(TwfSendBackEty twfSendBackEty, Integer resendType, String zpFlag) {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(twfSendBackEty.getWfId());
        TwfSendBackEty etyMain = new TwfSendBackEty();
        if (tworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(tworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(tworkFormBaseEty.getCallId());
            etyMain.setTapeId(tworkFormBaseEty.getTapeId());
            etyMain.setWfId(tworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if (!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(twfSendBackEty.getSeqCode());
        etyMain.setSeqName(twfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(twfSendBackEty.getSendDesc());
        etyMain.setSdeptId(twfSendBackEty.getSdeptId());
        etyMain.setSdeptName(twfSendBackEty.getSdeptName());
        etyMain.setSuserNo(twfSendBackEty.getSuserNo());
        etyMain.setSuserName(twfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(twfSendBackEty.getSendRemark());
        etyMain.setSattachPath(twfSendBackEty.getSattachPath());
        etyMain.setSattachName(twfSendBackEty.getSattachName());
        etyMain.setSendSpare(twfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(twfSendBackEty.getDealName());
        etyMain.setBackLimit(twfSendBackEty.getBackLimit());
        etyMain.setIsGoBack(twfSendBackEty.getIsGoBack());
        //TODO：promisesTime不清楚怎么来的
        etyMain.setPromisesTime(twfSendBackEty.getBackLimit());
        if (twfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (twfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(twfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(twfSendBackEty.getSbdeptName());
        //重新派单，页面上拿不到父派单id
        Integer pid = twfSendBackEty.getPid();
        if(!"304".equals(deptId) && (pid == null || pid <= 0)) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<TwfSendBackEty> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", twfSendBackEty.getWfId());
            queryWrapper.eq("SBDeptId", deptId);
            queryWrapper.orderByDesc("pkId");
            List<TwfSendBackEty> list = wfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        etyMain.setPid(pid);
        int row = 0;
        boolean flag = false;
        //拟派多个部门
        if(twfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = twfSendBackEty.getSbdeptId().split(",");
            String[] names = twfSendBackEty.getSbdeptName().split(",");
            String[] zpFlags = zpFlag.split(",");
            String sendDesc = twfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                etyMain.setSendDesc(sendDesc.replace(twfSendBackEty.getSbdeptName(),names[i]));
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                etyMain.setSdeptId(twfSendBackEty.getSdeptId());
                etyMain.setSdeptName(twfSendBackEty.getSdeptName());
                etyMain.setPid(pid);
                if (zpFlags[i].equals("10")){
                    etyMain.setSendSpare("1"); //直派
                    sendSonCtrl.directWF(etyMain,user);
                }else {
                    flag = wfSendBackService.save(etyMain);
                    if (flag) {
                        row = 1;
                        // 记录电话派单操作日志
                        //todo 日志
                        TworkFormLogEty etyLog = new TworkFormLogEty();
                        etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                        etyLog.setOpDeptNo(deptId);
                        etyLog.setOpDeptName(user.getDeptName());
                        etyLog.setOpUserNo(user.getUserNo());
                        etyLog.setOpUserName(user.getUserName());
                        etyLog.setOpAction("提交初稿");
                        etyLog.setOpBtnId(-1);
                        String temp = "";
                        String desc = "";
                        temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                        desc = "主办：";
                        desc += temp;
                        etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                        etyLog.setWsOpen(1); //website ShowFlag
                        etyLog.setOpDesc("提交内容概要：" + desc);
                        etyLog.setEffectFlag(1);
                        telWFLogService.save(etyLog);
                    }
                }
                //更新父级派单状态 etyMain新增下派单子的id
                commonDao.proTsubBackState(twfSendBackEty.getWfId(),etyMain.getPkId());
            }
        }
        //拟派一个部门
        else {
            if (zpFlag != null && zpFlag.equals("0")) {//派给一个部门
                flag = wfSendBackService.save(etyMain);
                if (flag) {
                    row = 1;
                    // 记录电话派单操作日志
                    //todo 日志
                    TworkFormLogEty etyLog = new TworkFormLogEty();
                    etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(deptId);
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnId(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交内容概要：" + desc);
                    etyLog.setEffectFlag(1);
                    telWFLogService.save(etyLog);
                }
            }else {
                //xnb直派
                etyMain.setSendSpare("1"); //直派
                sendSonCtrl.directWF(etyMain,user);
            }
            //更新父级派单状态 etyMain新增下派单子的id
            commonDao.proTsubBackState(twfSendBackEty.getWfId(),etyMain.getPkId());
        }
        return toAjax(row);
    }


    /**
     * Xnb直派工单
     */
    private void simulacrumXnb(TwfSendBackEty twfSendBackEty,String deptId){
        SysUser user = ShiroUtils.getSysUser();
        //区县政府
        TwfSendBackEty sbQX = new TwfSendBackEty();
        //xnb直派 给区县初始化一条记录
        sbQX.setGetDealPk(twfSendBackEty.getGetDealPk());
        sbQX.setCallId(twfSendBackEty.getCallId());
        sbQX.setTapeId(twfSendBackEty.getTapeId());
        sbQX.setWfId(twfSendBackEty.getWfId());
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        sbQX.setOriLevel(oriLevel);
        sbQX.setSeqCode(twfSendBackEty.getSeqCode());
        sbQX.setSeqName(twfSendBackEty.getSeqName());
        //已派下级
        sbQX.setSendState(23);
        sbQX.setSortCode(twfSendBackEty.getSortCode());
        sbQX.setSortName(twfSendBackEty.getSortName());
        sbQX.setDealCode(twfSendBackEty.getDealCode());
        sbQX.setDealName(twfSendBackEty.getDealName());
        sbQX.setSbdeptId(twfSendBackEty.getSbdeptId());
        sbQX.setSbdeptName(twfSendBackEty.getSbdeptName());
        sbQX.setSendDesc(twfSendBackEty.getSendDesc());
        sbQX.setSendTime(twfSendBackEty.getSendTime());
        sbQX.setBackLimit(twfSendBackEty.getBackLimit());
        sbQX.setSendRemark(twfSendBackEty.getSendRemark());
        sbQX.setSendSpare("1");
        sbQX.setSattachPath(twfSendBackEty.getSattachPath());
        sbQX.setSdeptId(user.getDeptId().toString());
        sbQX.setSdeptName(user.getDeptName());
        //拟派多个部门
        if(twfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = twfSendBackEty.getSbdeptId().split(",");
            String[] names = twfSendBackEty.getSbdeptName().split(",");
            String sendDesc = twfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                sbQX.setSbdeptId(ids[i]);
                sbQX.setSbdeptName(names[i]);
                sbQX.setSendDesc(sendDesc.replace(twfSendBackEty.getSbdeptName(),names[i]));
                wfSendBackService.save(sbQX);
            }
        }
        //拟派一个部门
        else {
            wfSendBackService.save(sbQX);
        }
    }

    /**
     * 智能派单
     *
     * @param
     * @return
     */
    @RequestMapping("Intelligent")
    @RepeatSubmit
    public AjaxResult Intelligent(TworkFormBaseEty workFormBaseEty) throws ParseException {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        TworkFormBaseEty formBaseEty = workFormBaseService.getById(workFormBaseEty.getPkId());

        TwfSendBackEty twfSendBackEty = formBaseEty.getTwfSendBackEty();
        twfSendBackEty.setSbdeptName(workFormBaseEty.getMark());
        String deptNo=commonService.selectDeptShort(twfSendBackEty.getSbdeptName());
        twfSendBackEty.setSbdeptId(deptNo);
        twfSendBackEty.setSdeptId(deptId);
        twfSendBackEty.setSdeptName(user.getDeptName());
        twfSendBackEty.setSuserNo(user.getUserNo());
        twfSendBackEty.setSuserName(user.getUserName());
        twfSendBackEty.setWfId(formBaseEty.getPkId());
        twfSendBackEty.setGetDealPk(formBaseEty.getGetDealPk());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        twfSendBackEty.setBackLimit(sdf.parse(commonService.getNxetBackLimit(5)));
        twfSendBackEty.setSeqName("初次交办");
        twfSendBackEty.setSeqCode("10");
        twfSendBackEty.setSortCode("11");
        twfSendBackEty.setSortName("主办");
        twfSendBackEty.setDealCode("11");
        twfSendBackEty.setDealName("研究办理");
        twfSendBackEty.setFpDirect(0);
        twfSendBackEty.setSendDesc("请 "+twfSendBackEty.getSbdeptName()+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");

        TwfSendBackEty sbDir = new TwfSendBackEty();
        sbDir = twfSendBackEty;
        sbDir.setSendState(10);  //未签收
        sbDir.setSendSpare("1");
        TwfSendBackEty sbQX = new TwfSendBackEty(); //区县政府

        try {
            if (twfSendBackEty.getFpDirect() > 0) {//xnb直派
                wfSendBackService.save(sbQX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(twfSendBackEty.getWfId());
        TwfSendBackEty etyMain = new TwfSendBackEty();
        if (tworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(tworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(tworkFormBaseEty.getCallId());
            etyMain.setTapeId(tworkFormBaseEty.getTapeId());
            etyMain.setWfId(tworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(twfSendBackEty.getSeqCode());
        etyMain.setSeqName(twfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(twfSendBackEty.getSendDesc());
        etyMain.setSdeptId(twfSendBackEty.getSdeptId());
        etyMain.setSdeptName(twfSendBackEty.getSdeptName());
        etyMain.setSuserNo(twfSendBackEty.getSuserNo());
        etyMain.setSuserName(twfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(twfSendBackEty.getSendRemark());
        etyMain.setSattachPath(twfSendBackEty.getSattachPath());
        etyMain.setSattachName(twfSendBackEty.getSattachName());
        etyMain.setSendSpare(twfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(twfSendBackEty.getDealName());
        etyMain.setBackLimit(twfSendBackEty.getBackLimit());
//        bDeptId = arrDetpIdX[i];
//        bDeptName = arrDetpNameX[i];
        if (twfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (twfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(twfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(twfSendBackEty.getSbdeptName());
        int row = 0;
        boolean flag = wfSendBackService.save(etyMain);
        if (flag) {
            row = 1;
            // 记录电话派单操作日志
            //todo 日志
            TworkFormLogEty etyLog = new TworkFormLogEty();
            etyLog.setWfId(twfSendBackEty.getWfId()); //[tWorkFormBase]PkId
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpAction("提交初稿");
            etyLog.setOpBtnId(-1);
            String temp = "";
            String desc = "";
            temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
            if (temp.lastIndexOf(",") > 0)
                temp = temp.substring(0, temp.length() - 1);
            desc = "主办：";
            desc += temp;
            etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
            etyLog.setWsOpen(1); //website ShowFlag
            etyLog.setOpDesc("提交内容概要：" + desc);
            etyLog.setEffectFlag(1);
            telWFLogService.save(etyLog);
        }
        return toAjax(row);
    }

    /**
     * 拟派工单 列表显示
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("simulacrumList/{wfId}")
    public TableDataInfo simulacrumList(@PathVariable("wfId") Integer wfId) {
        startPage();
        List<TwfSendBackEty> list = wfSendBackService.selectByWfId(wfId);
        return getDataTable(list);
    }

    /**
     * 查询派发部门列表
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("distributeDept")
    public TableDataInfo distributeDept() {
        List<Map<String, String>> list = deptService.selectDistribute();
        return getDataTable(list);
    }

    /**
     * 查询派发部门 下级列表
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("sltDept")
    public TableDataInfo sltDept() {
        List<Map<String, String>> list = deptService.selectSltDept();
        return getDataTable(list);
    }


    /**
     * 审核工单
     *
     * @param twfSendBackEty
     * @return
     */
    @PostMapping("examine")
    @RepeatSubmit
    public AjaxResult examine(TwfSendBackEty twfSendBackEty) {
        SysUser user = ShiroUtils.getSysUser();
        TworkFormLogEty tworkFormLogEty = twfSendBackEty.getTworkFormLogEty();
        tworkFormLogEty.setOpUserNo(user.getUserNo());
        tworkFormLogEty.setOpUserName(user.getUserName());
        tworkFormLogEty.setOpDeptNo(user.getDeptId().toString());
        tworkFormLogEty.setOpDeptName(user.getDeptName());
        tworkFormLogEty.setOpBtnId(-1);
        twfSendBackEty.setSdeptName(user.getDeptName());
        twfSendBackEty.setSdeptId(user.getDeptId().toString());
        twfSendBackEty.setSuserNo(user.getUserNo());
        twfSendBackEty.setSuserName(user.getUserName());
        String temp = "";
        if (twfSendBackEty.getBackState() == 22) {
            temp = "不通过";
            twfSendBackEty.setBackRemark("不同意");
        }
        else {
            temp = "通过";
            twfSendBackEty.setBackRemark("同意");
        }
        temp = "审查" + twfSendBackEty.getSbdeptName() + "办理结果（" + temp + "）";
        tworkFormLogEty.setOpDesc(temp);
        telWFLogService.save(tworkFormLogEty);
        return toAjax(wfSendBackService.updateSendBack(twfSendBackEty));
    }

    /**
     * 根据id 进行多选删除 和单个删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String... ids) {
        return toAjax(wfSendBackService.deleteByIds(ids));
    }

    /**
     * 进入回访页面
     * @return
     */
    @GetMapping("sendBackRecord/{wfId}")
    public ModelAndView sendBackRecord(@PathVariable("wfId") Integer wfId,ModelMap map) {
        map.addAttribute("wfId",wfId);
        return new ModelAndView(prefix + "/sendBackRecord");
    }

    /**
     * 进入回访记录详情页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/sendBackRecordDetail/{wfId}/{pkId}")
    public ModelAndView sendBackRecordDetail(@PathVariable("wfId") Integer wfId, @PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        TworkFormBaseEty tworkFormBaseEty = workFormBaseService.getById(wfId);
        TwfSendBackEty sendBackEty = wfSendBackService.getById(pkId);
        tworkFormBaseEty.setTwfSendBackEty(sendBackEty);
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", tworkFormBaseEty);
        map.put("wfId", tworkFormBaseEty.getPkId());
        map.put("sdeptName", sendBackEty.getSdeptName());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());

        return new ModelAndView(prefix+"/sendBackRecordDetail");
    }

    /**
     * 派发下级部门
     * @param sender 拟派工单信息
     */
    @PostMapping("/sendSon")
    public void sendSon(TwfSendBackEty sender){
        String desc = "";
        //当前用户登录信息
        SysUser user = getSysUser();
        //更新工单当前信息
        UpdateWrapper<TworkFormBaseEty> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PkId", sender.getWfId());
        updateWrapper.set("WsUFlag", 1);
        updateWrapper.set("CrtStepId", 400);
        updateWrapper.set("CrtStepName", "市级部门处理中");
        updateWrapper.set("CrtStepTime", DateUtils.getNowDate());
        workFormBaseService.update(null, updateWrapper);
        //更新当前派单情况
        UpdateWrapper<TwfSendBackEty> wrapper = new UpdateWrapper<>();
        wrapper.eq("PkId", sender.getPkId());
        wrapper.set("SendState", 23);
        wfSendBackService.update(null, wrapper);

        TworkFormLogEty etyLog = new TworkFormLogEty();
        //[tWorkFormBase]PkId
        etyLog.setWfId(sender.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setOpAction("派单到下级部门");
        etyLog.setOpBtnId(-1);
        desc = sender.getSbdeptName();
        etyLog.setWsDesc("转办工单（" + desc + "）");
        etyLog.setWsOpen(1);
        etyLog.setOpDesc("提交到下级部门（" + desc + "）");
        etyLog.setEffectFlag(1);
        telWFLogService.save(etyLog);
    }

    /**
     * 2023/1/10
     * 修改TwfSendBackEty工单信息
     * @param twfSendBackEty
     * @return 响应结果
     */
    @PostMapping("/editSendBackDept")
    public AjaxResult editSendBackDept(TwfSendBackEty twfSendBackEty) {
        //保存响应结果
        boolean flag = false;
        SysUser user = ShiroUtils.getSysUser();
        TworkFormLogEty etyLog = new TworkFormLogEty();
        if(twfSendBackEty != null) {
            //拟派多个部门
            TwfSendBackEty updateSendBackEty = new TwfSendBackEty();
            BeanUtils.copyBeanProp(updateSendBackEty, twfSendBackEty);
            if (StringUtils.isNotEmpty(twfSendBackEty.getSbdeptId())) {
                String[] arrDetpIdX = twfSendBackEty.getSbdeptId().split(",");
                String[] arrDetpNameX = twfSendBackEty.getSbdeptName().split(",");
                for (int i = 0; i < arrDetpIdX.length; i++) {
                    updateSendBackEty.setSbdeptId(arrDetpIdX[i]);
                    updateSendBackEty.setSbdeptName(arrDetpNameX[i]);
                    try {
                        // 默认第一条为修改
                        if ( i == 0) {
                            UpdateWrapper<TwfSendBackEty> sbWrapper = new UpdateWrapper<>();
                            sbWrapper
                                    .set("SeqCode", updateSendBackEty.getSeqCode())
                                    .set("SeqName", updateSendBackEty.getSeqName())
                                    .set("SbdeptId", updateSendBackEty.getSbdeptId())
                                    .set("SbdeptName", updateSendBackEty.getSbdeptName())
                                    .set("SortCode", updateSendBackEty.getSortCode())
                                    .set("SortName", updateSendBackEty.getSortName())
                                    .set("DealCode", updateSendBackEty.getDealCode())
                                    .set("DealName", updateSendBackEty.getDealName())
                                    .set("SendDesc", updateSendBackEty.getSendDesc())
                                    .set("BackLimit", updateSendBackEty.getBackLimit())
                                    .set("SendRemark", updateSendBackEty.getSendRemark())
                                    .set("isDelay", updateSendBackEty.getIsDelay())
                                    .eq("PkId", updateSendBackEty.getPkId());
                            //执行修改方法
                            flag = wfSendBackService.update(sbWrapper);
                            if (flag){
                                etyLog.setWfId(updateSendBackEty.getWfId());
                                etyLog.setOpDeptNo(user.getDeptId().toString());
                                etyLog.setOpDeptName(user.getDeptName());
                                etyLog.setOpUserNo(user.getUserNo());
                                etyLog.setOpUserName(user.getUserName());
                                String temp = "调整办理部门及要求(" + updateSendBackEty.getSbdeptName() + ")";
                                etyLog.setOpAction("修改");
                                etyLog.setOpBtnId(-1);
                                etyLog.setWsDesc(temp);
                                etyLog.setWsOpen(1);
                                etyLog.setOpDesc(temp);
                                etyLog.setEffectFlag(-1);
                                flag =  telWFLogService.save(etyLog);
                            }
                        } else {
                            // 新增派单
                            updateSendBackEty.setSendTime(new Date());
                            // 修改截至日期
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            updateSendBackEty.setBackLimit(sdf.parse(commonService.getNxetBackLimit(5)));
                            flag = wfSendBackService.save(updateSendBackEty);
                            etyLog.setWfId(updateSendBackEty.getWfId()); //[tWorkFormBase]PkId
                            etyLog.setOpDeptNo(user.getDeptId().toString());
                            etyLog.setOpDeptName(user.getDeptName());
                            etyLog.setOpUserNo(user.getUserNo());
                            etyLog.setOpUserName(user.getUserName());
                            etyLog.setOpAction("提交初稿");
                            etyLog.setOpBtnId(-1);
                            String temp = "";
                            String desc = "";
                            temp = updateSendBackEty.getSbdeptName() != null ? updateSendBackEty.getSbdeptName() : "";
                            desc = "主办：";
                            desc += temp;
                            etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                            etyLog.setWsOpen(1); //website ShowFlag
                            etyLog.setOpDesc("提交内容概要：" + desc);
                            etyLog.setEffectFlag(1);
                            flag =  telWFLogService.save(etyLog);
                        }
                    } catch (Exception e) {
                        this.logger.debug("add main [tWfSendBack] fail: " + e.getMessage());
                        return AjaxResult.error();
                    }
                }
            }
        }
        return toAjax(flag);
    }

}
